import cv2
import numpy as np
from PIL import Image


def initialize_camera(camera_index=1):
    """初始化并返回摄像头对象"""
    cap = cv2.VideoCapture(camera_index)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    return cap


def capture_frame(cap):
    """捕获一帧图像并转换为PIL格式"""
    ret, frame = cap.read()
    if not ret:
        return None, None

    # 转换颜色空间
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    pil_image = Image.fromarray(rgb_frame)
    return frame, pil_image


def display_frame(frame, label, cooldown, fps, status):
    """在窗口中显示帧和相关信息"""
    # 显示包装类型
    cv2.putText(frame, f"包装类型: {label}", (20, 50),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    # 显示冷却时间
    if cooldown > 0:
        cv2.putText(frame, f"冷却: {cooldown:.1f}s", (20, 100),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 100, 255), 2)

    # 显示FPS
    cv2.putText(frame, f"FPS: {fps:.1f}", (20, 150),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)

    # 显示操作状态
    cv2.putText(frame, f"状态: {status}", (20, 200),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)

    cv2.imshow('快递包装识别与机械臂操作', frame)